CSS Text Shadow Mouse Move Effect


Posted by wayne201299 on 2023-10-02

DEMO

計算滑鼠移動的相對位置來決定陰影位置及樣式

實作

  1. 監聽滑鼠移動事件,並建立shadow方法抓取目前滑鼠在element上的位置

     const hero = document.querySelector(".hero");
     const text = hero.querySelector("h1");
     hero.addEventListener("mousemove", shadow);
    
  2. 設定陰影位置,首先篩選監聽到的element,去掉非父層的element,進行陰影位置計算

     const walk = 200; // 100px
    
     function shadow(e) {
         const { offsetWidth: width, offsetHeight: height } = hero;
         let { offsetX: x, offsetY: y } = e;
         // this returns the current element=> hero
         if (this !== e.target) {
             x = x + e.target.offsetLeft;
             y = y + e.target.offsetTop;
         }
    
         const xWalk = Math.round((x / width) * walk - walk / 2);
         const yWalk = Math.round((y / height) * walk - walk / 2);
         text.style.textShadow = `${xWalk}px ${yWalk}px 0 rgba(255,0,255,0.7), ${
             xWalk * -1
         }px ${yWalk}px 0 rgba(0,255,255,0.7), ${yWalk}px ${
             xWalk * -1
         }px 0 rgba(255,255,0,0.7), ${yWalk * -1}px ${xWalk}px 0 rgba(0,0,255,0.7)`;
     }
    

這邊要注意,因為hero是包著h1,對於瀏覽器來說,實際上監聽到的element會有兩個

知識點

  • contenteditable可以讓元素變成可編輯
  • offset表示相對父元素的距離,有上下左右可取
  • text-shadow: [offset-x] [offset-y] [blur-radius] [color];

#javascript #css







Related Posts

練習讓我們完成各種夢想 — 刻意練習

練習讓我們完成各種夢想 — 刻意練習

JS30 Day 30 筆記

JS30 Day 30 筆記

W23_前端框架 Redux 學習筆記

W23_前端框架 Redux 學習筆記


Comments